/*
 * @Author: myw
 * @Email: 516378746@qq.com
 * @Date: 2020-03-11 09:44:14
 * @Descripttion: tab 页签
 */
import { Component, OnInit, Injectable, ElementRef } from '@angular/core';
import { ActivatedRoute, Router, NavigationEnd, ActivationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
import Swiper from 'swiper';
import { NzDropdownMenuComponent, NzContextMenuService } from 'ng-zorro-antd';
import { HCommonService } from '../h-common.service';
import { SimpleReuseStrategy } from 'src/app/http-interceptors/simpleReuseStrategy.interceptor';

@Component({
    selector: 'app-tabs',
    templateUrl: './tabs.component.html',
    styleUrls: ['./tabs.component.scss'],
    providers : [SimpleReuseStrategy]
})
export class TabsComponent implements OnInit {

    private allTabs = [];
    selectTabIndex = -1;
    tabSwiper: Swiper;
    dropdownMenuTop = "0";
    dropdownMenuLeft = "0";
    contextActived: { [key: string]: any } = {};

    constructor(
        private activedRoute: ActivatedRoute,
        private router: Router,
        private nzContextMenuService: NzContextMenuService,
        private commonService : HCommonService,
        private simpleReuseStrategy : SimpleReuseStrategy,
        private el : ElementRef
    ) {
        this.router.events.subscribe(event => {
            if (event instanceof ActivationEnd) {
                let _config = event.snapshot.routeConfig;
                if (_config.path !== '' && _config.data.isLastLevel) {
                    this.actionTab(_config);
                    this.commonService.setDocTitle(_config.data.title);
                }
            }
        })
    }
    

    ngOnInit() {
        this.initSwiper();
    }

    prevSlider() {
        this.tabSwiper.slidePrev();
    }
    nextSlider() {
        this.tabSwiper.slideNext();
    }
    initSwiper() {
        this.tabSwiper = new Swiper('.swiper-container', {
            slidesPerView: "auto",
            observer: true,             //修改swiper自己或子元素时，自动初始化swiper
        })
    }
    addTab(config) {
        let _uid = config.data.uid;
        this.allTabs[_uid] = {
            url: this.router.url,
            title: config.data.title,
            uid: _uid,
            componentName : config.component.name
        }
        this.selectTabIndex = _uid;
    }
    actionTab(config) {
        let _uid = config.data.uid;
        let _tab = this.allTabs[_uid];
        if (_tab) {
            this.activeRoute(_tab)
        } else {
            this.addTab(config);
        }

        if (this.tabSwiper) {
            let _sliderArr = this.delEmpty(this.allTabs);
            let _sliderIndex = this.activeSliderIndex(_sliderArr, config.data);
            this.tabSwiper.slideTo(_sliderIndex, 1000, false);
        }
    }
    activeRoute(tab) {
        this.router.navigateByUrl(tab.url).finally();
        this.selectTabIndex = tab.uid;

        let _maskContainer = document.getElementsByClassName("cdk-overlay-container");
        let _mask = document.getElementsByClassName("cdk-overlay-backdrop");
        let _maskOptions = document.getElementsByClassName("cdk-overlay-connected-position-bounding-box");
        /* console.log( _maskContainer );
        console.log( _mask );
        console.log( _maskOptions ); */
        if( _mask.length != 0 && _maskOptions.length != 0 ){
            _maskContainer[0].removeChild(_mask[0]);
            _maskContainer[0].removeChild(_maskOptions[0]);
        }
    }

    delEmpty(arr) {
        return arr.filter(item => {
            return item
        })
    }
    activeSliderIndex(arr, tab) {
        let _index: number;
        arr.forEach((item, index) => {
            if (item.uid === tab.uid) {
                _index = index
            }
        })
        return _index
    }



    switchTab(tab) {
        this.activeRoute(tab);
    }
    closeCurTab(e, tab) {
        e.stopPropagation();
        let _uid = tab.uid;
        
        let _leftItem = this._isPrevEmpty(_uid);
        let _rightItem = this._isNextEmpty(_uid);

        this.simpleReuseStrategy.deleteRouteSnapshot(tab.url, tab.componentName)

        if (this.selectTabIndex === _uid) {
            if (!_leftItem && _rightItem) {
                this.activeRoute(_rightItem);
            }
            if (_leftItem && !_rightItem) {
                this.activeRoute(_leftItem);
            }
            if (_leftItem && _rightItem) {
                this.activeRoute(_leftItem);
            }
        }
        if (_leftItem || _rightItem) {
            this.allTabs[_uid] = null;
        }
        
    }
    _isPrevEmpty(uid) {
        let _r = false;
        for (let i = uid - 1; i > 0; i--) {
            if (this.allTabs[i]) {
                _r = true;
                return this.allTabs[i];
            }
        }
        return _r
    }
    _isNextEmpty(uid) {
        let _r = false;
        for (let i = uid + 1; i < this.allTabs.length; i++) {
            if (this.allTabs[i]) {
                _r = true;
                return this.allTabs[i];
            }
        }
        return _r
    }

    contextMenu($event: MouseEvent, menu: NzDropdownMenuComponent, tab): void {
        $event.preventDefault();
        this.nzContextMenuService.create($event, menu);
        this.dropdownMenuTop = "-86px";
        this.dropdownMenuLeft = $event.clientX - 200 + "px";
        this.contextActived = tab;
    }
    contextCloseCur(e) {
        this.closeCurTab(e, this.contextActived)
    }
    contextCloseOther() {
        this.allTabs = [];
        let _uid = this.contextActived.uid;
        this.allTabs[_uid] = this.contextActived;
        this.selectTabIndex = _uid;
    }
}
